package com.cordwood.helper.localdb;

import lombok.val;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import redis.embedded.RedisServer;

import java.util.Objects;

public class EmbeddedRedisBootstrap implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        val host = Objects.requireNonNull(event.getEnvironment().getProperty("spring.redis.host"));
        int port = Objects.requireNonNull(event.getEnvironment().getProperty("spring.redis.port", Integer.class));
        if (Objects.equals(host, "localhost") || Objects.equals(host, "127.0.0.1") && SocketUtils.isPortAvailable(port)) {
            Assert.isTrue(!StringUtils.hasLength(event.getEnvironment().getProperty("spring.redis.password")),
                    "Redis password must null to start embedded redis"
            );
            bootstrap(port);
        }
    }

    private void bootstrap(Integer port) {

        RedisServer.builder()
                .port(port)
                .setting("maxmemory 16M")
                .build()
                .start();
    }
}
